// import type { ProRouterPlugin } from '../plugin'
// import { inject, toValue } from 'vue'
// import { viewDepthKey } from 'vue-router'

import { inject, toValue, type App } from "vue"
import { viewDepthKey, type Router } from "vue-router"

declare module 'vue-router' {
  interface Router {
    /**
     * 解析嵌套路由，传递给 router-view 的 route prop
     */
    resolveNestedRoute: () => RouteLocationNormalizedLoaded
  }
}

export default function nestedRouteRenderPlugin(router: Router, runWithApp: (callback: (app: App) => void) => void) {

  router.resolveNestedRoute = () => {
    let injectedViewDepth: number
   
    runWithApp((app) => {
      app.runWithContext(() => {
         console.log(injectedViewDepth)
        injectedViewDepth = toValue(inject(viewDepthKey, 0))
      })
    })
    const route = router.currentRoute.value
    const req = {
      ...route,
      matched: route.matched.map((item, index, arr) => {
        // console.log(injectedViewDepth)
        if (index > injectedViewDepth && index !== arr.length - 1) {
          return {
            ...item,
            components: undefined,
          }
        }
        return item
      }),
    }
    return req;
  }

}
